package com.example.dps;

import java.text.DecimalFormat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TextView;



public class ViewSavingsActivity extends Activity{
	
	DBHelper dbhelper;
	AccountDBHelper accountDBHelper;
	WebHelper webHelper;
	HistoryHelper historyHelper;
	TipsDBHelper tipsDBHelper;
	
	DecimalFormat formatter = new DecimalFormat("#,###,###");
	
	/**Layout containing the Tips Table **/
	TableLayout tipsTable = null;
	
	/** ID of current layout (R.layout.X) **/
	int layoutID = 0;
	
	/** rectangle containing the bounds of the button last clicked **/
	private Rect rect;
	 
	
	/**
	 * creates the option menu. (logout/settings/etc)
	 */

	
	@Override
	 public void onWindowFocusChanged(boolean hasFocus) {
		  // TODO Auto-generated method stub
		  super.onWindowFocusChanged(hasFocus);
		  if(this.layoutID == R.layout.view_savings_activity) animateHouse();
	  
	 }
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		dbhelper = new DBHelper(this);
		
		accountDBHelper = new AccountDBHelper(this);
		
		webHelper = new WebHelper(this);
		
		historyHelper = new HistoryHelper(this);
		
		tipsDBHelper = new TipsDBHelper(this);
		

		


	}
	

	
	public void onResume(){
		super.onResume();
		
		/** make sure account has been created **/
		if(this.dbhelper.getBoolean(DBHelper.COLUMN_ACCOUNT_CREATED) == false){
			//redirect to add account page
			Intent intent = new Intent(ViewSavingsActivity.this, TabRoot.class);
			intent.putExtra("START_TAB", "add_money");
			startActivity(intent);
			return;
			
		}
		
		//if(this.webHelper.authenticate("view_savings")){
			this.layoutID = R.layout.view_savings_activity;
			
			this.webHelper.getAccountInfo();
			
			changeToLayout(this.layoutID);
		//}

		
//		if(this.layoutID == R.layout.view_savings_activity){
//			restoreDatabaseValues();
//			
//			addSavingsTip();
//			
//			ScrollView sv = (ScrollView) this.findViewById(R.id.scrollView);
//			if(sv!=null) sv.scrollTo(0,0);
//		}
		
	}
	
	public void onGetAccountInfo(Boolean result){
		
		if(!result){
			Intent intent = new Intent(this, LoginActivity.class);
			intent.putExtra("START_TAB", "view_savings");
			this.startActivity(intent);
		}
		else{
			if(this.layoutID == R.layout.view_savings_activity){
				restoreDatabaseValues();
				
				addSavingsTip();
				
				ScrollView sv = (ScrollView) this.findViewById(R.id.scrollView);
				if(sv!=null) sv.scrollTo(0,0);
			}
			
		}
		
	}
	
	
	public void restoreDatabaseValues(){
		/** get the ammount saved in the DPS account **/
		int saved = (int) accountDBHelper.getDPSAccountAsAccount().amount;
		
		/** get the goal stored in the database helper **/
		int total = (int) dbhelper.selectGoalTotal();
		
		//String deadline = dbhelper.selectGoalDeadline();
		
		TextView goalTotalText = (TextView)findViewById(R.id.goalTotalText);
		TextView goalSavedText = (TextView)findViewById(R.id.goalSavedText);
		TextView bonusPointsValue = (TextView) findViewById(R.id.bonusPointsValue);
		
		goalTotalText.setText("$" + formatter.format(total));
		
		goalSavedText.setText("$" + formatter.format(saved));
		
		bonusPointsValue.setText("0");
	}
	
	public void addOnClickListeners(){
		
		if(this.layoutID==R.layout.history_layout){
			
			ImageButton backButton = (ImageButton) findViewById(R.id.backButton);
			
			backButton.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					
					changeToLayout(R.layout.view_savings_activity);
					
				}
				
			});
			
			backButton.setOnTouchListener(new OnTouchListener(){
				

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					ImageView image = (ImageView) v;
					
					// TODO Auto-generated method stub
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						image.setImageDrawable(v.getResources().getDrawable(R.drawable.back_button_clicked));
						rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
					}
					else if(event.getAction() == MotionEvent.ACTION_UP){
						image.setImageDrawable(v.getResources().getDrawable(R.drawable.back_button));
					}
					else if(event.getAction() == MotionEvent.ACTION_CANCEL){
						image.setImageDrawable(v.getResources().getDrawable(R.drawable.back_button));
					}
					
					return false;
				}

			});
			
		}
		
		if(this.layoutID == R.layout.view_savings_activity){
			TextView accountSettingsBtn = (TextView) findViewById(R.id.viewSavingAccountSettingsBtnText);
			
			accountSettingsBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					/** TODO temporary link to account setup **/
					
					Intent intent = new Intent(ViewSavingsActivity.this, SettingsActivity.class);
					ViewSavingsActivity.this.startActivity(intent);
					
				}
				
			});
			
			accountSettingsBtn.setOnTouchListener(new OnTouchListener(){

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					
					TextView view = (TextView) v;
					
					//get button root
					FrameLayout root = (FrameLayout) view.getParent().getParent();
					ImageView image = (ImageView) root.getChildAt(0);
					
					
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_yellow_clicked));
						rect = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
					}
					else if(event.getAction() == MotionEvent.ACTION_UP){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_yellow));
					}
					else if(event.getAction() == MotionEvent.ACTION_CANCEL){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_yellow));
					}
					
					
					return false;
				}
				
			});
			
			TextView addMoneyBtn = (TextView) findViewById(R.id.viewSavingsAddMoneyBtnText);
			
			addMoneyBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					Log.e("View Savings", "Clicked 'Add Money' button");
					Intent intent = new Intent(ViewSavingsActivity.this, TabRoot.class);
					//Log.d("Main Activity", "Starting Mortgage Calc Activity");
					intent.putExtra("START_TAB", "add_money");
					ViewSavingsActivity.this.startActivity(intent);
					
				}
				
			});
			
			addMoneyBtn.setOnTouchListener(new OnTouchListener(){

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					
					TextView view = (TextView) v;
					
					//get button root
					FrameLayout root = (FrameLayout) view.getParent().getParent();
					ImageView image = (ImageView) root.getChildAt(0);
					
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_blue_clicked));
					}
					else if(event.getAction() == MotionEvent.ACTION_UP){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_blue));
					}
					else if(event.getAction() == MotionEvent.ACTION_CANCEL){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_blue));
					}
					
					return false;
				}
				
			});
			
			
			TextView historyBtn = (TextView) findViewById(R.id.viewSavingHistoryBtnText);
			
			historyBtn.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					Log.e("View Savings", "Clicked 'History' button");
					
					/** TODO change layout to view_history **/
					
					changeToLayout(R.layout.history_layout);
					
				}
				
			});
			
			historyBtn.setOnTouchListener(new OnTouchListener(){

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					
					TextView view = (TextView) v;
					
					//get button root
					FrameLayout root = (FrameLayout) view.getParent().getParent();
					ImageView image = (ImageView) root.getChildAt(0);
					
					if(event.getAction() == MotionEvent.ACTION_DOWN){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_orange_clicked));
					}
					else if(event.getAction() == MotionEvent.ACTION_UP){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_orange));
					}
					else if(event.getAction() == MotionEvent.ACTION_CANCEL){
						image.setImageDrawable(view.getResources().getDrawable(R.drawable.savings_btn_orange));
					}
					
					return false;
				}
				
			});
			
		}
		
		
	}
	
	/**
	 * fills the house image, based on the amount saved
	 */
	public void animateHouse(){
		
		
		TextView moneySavedText = (TextView) findViewById(R.id.goalSavedText);
		TextView downPaymentGoalText = (TextView)findViewById(R.id.goalTotalText);
		
		double goal = Integer.parseInt(downPaymentGoalText.getText().toString().replace("$", "").replace(",", ""));
		double saved = Integer.parseInt(moneySavedText.getText().toString().replace("$", "").replace(",", ""));

		ImageView emptyView = (ImageView)findViewById(R.id.house_empty);
		ImageView fullView = (ImageView)findViewById(R.id.house_full);
		TextView percentageText = (TextView) findViewById(R.id.percentageValue);
		
		if(goal == 0 || saved == 0 || goal < 0 || saved < 0){
			// Assign new bitmap to ImageView
			
			fullView.setImageDrawable(null);
			emptyView.setImageDrawable(getResources().getDrawable(R.drawable.savings_house_empty));
			
			percentageText.setText("0%");
			
		}

		else{
			
			double percent = saved/goal;
			
			if(percent >= 1){
				
				fullView.setImageDrawable(getResources().getDrawable(R.drawable.savings_house_full));

				emptyView.setImageDrawable(null);
				
				percentageText.setText("100%");
			}
			else{
				/** set the percentage of the house completed to the Text View **/
				
				
				int percentInt = (int) (percent*100);
				percentageText.setText(percentInt + "%");
				
				// Set some constants
				final Bitmap empty = BitmapFactory.decodeResource(getResources(),R.drawable.savings_house_empty);
				final int empty_x = 0;
				final int empty_y = 0;
				final int empty_px = empty.getWidth();
				int empty_py = (int) (empty.getHeight()*(1-percent));
				
				final Bitmap full = BitmapFactory.decodeResource(getResources(),R.drawable.savings_house_full);
				final int full_x = 0;
				final int full_y = empty_py;
				final int full_px = full.getWidth();
				final int full_py = (int) (full.getHeight()*(percent));

				// Crop bitmap
				
				Bitmap emptyBitmap = Bitmap.createBitmap(empty, empty_x, empty_y, empty_px, empty_py, null, false);
				
				Log.e("animate house", "y = " + full_y + "height = " + full_py);
				Bitmap fullBitmap = null;
				if(full_py > 0){
					 fullBitmap = Bitmap.createBitmap(full, full_x, full_y, full_px, full_py, null, false);
				}

				// Assign new bitmap to ImageView

				emptyView.setImageBitmap(emptyBitmap);
				
				fullView.setImageBitmap(fullBitmap);
			}

		}

	}
	
	

	private int dpToPx(int dp)
	{
	    float density = getApplicationContext().getResources().getDisplayMetrics().density;
	    return Math.round((float)dp * density);
	}
	
	public void changeToLayout(int layout){
		
		this.layoutID = layout;
		
		this.setContentView(layout);
		
		
		if(layout == R.layout.view_savings_activity){
			restoreDatabaseValues();
			
			
//			/** Insert Tips Table **/
//			this.tipsTable = (TableLayout) findViewById(R.id.viewSavingsTipsTable);
//			
//			
//			LayoutInflater layoutInflater = (LayoutInflater) 
//			        this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
//			
//			
//			tipsTable.addView(layoutInflater.inflate(R.layout.tips_layout, tipsTable, false )); 
//			/**********************/
			
			addSavingsTip();
			
			animateHouse();
			
		}
		else if(layout == R.layout.history_layout){
			
			addHistoryList();
			
		}


		addOnClickListeners();
		
		
	}

	
	/**
	 * adds the transaction history to the listview in the activity
	 */
	public void addHistoryList(){
		Cursor cursor = historyHelper.getHistoryAsCursor();
		
		/** if there are Recurring Transfers **/
		/** add recurring transfers view **/
		if(cursor.moveToFirst()){

			
			ListView historyList = (ListView) findViewById(R.id.historyListView);
			historyList.setDivider(null);
			historyList.setDividerHeight(0);
			
			
			

			String[] fromColumns = {HistoryHelper.COLUMN_FROM, HistoryHelper.COLUMN_TO, HistoryHelper.COLUMN_AMOUNT, HistoryHelper.COLUMN_DATE};
			
			int[] toViews = { R.id.historyItemFrom, R.id.historyItemTo, R.id.historyItemAmount, R.id.historyItemDate};

			
			
			SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
			        R.layout.history_layout_list_item, cursor, fromColumns, toViews, 0);
			
			historyList.setAdapter(adapter);
			
			//Utility.setListViewHeightBasedOnChildren(historyList);
		}
	}
	
	public void addSavingsTip(){
		
		/** Insert Tips Table **/
		this.tipsTable = (TableLayout) findViewById(R.id.tipsTable);
		
		this.tipsTable.removeAllViews();
		
		LayoutInflater layoutInflater = (LayoutInflater) 
		        this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		
		
		tipsTable.addView(layoutInflater.inflate(R.layout.tips_layout, tipsTable, false )); 
		/**********************/
		
		TextView titleText = (TextView) this.tipsTable.findViewById(R.id.tipTitle);
		
		TextView tipText = (TextView) this.tipsTable.findViewById(R.id.tipText);
		
		Tip tip = this.tipsDBHelper.getTip();
		
		if(tip != null){
			titleText.setText(tip.title);
			tipText.setText(tip.text);
		}
		else Log.e("null tip", "null tip");
		
		
		
		
		
	}
	
	
}
